#include <iostream>
#include "Common.hpp"
#include "InetAddr.hpp"
#include "log.hpp"
#include <unistd.h>
#include <functional>
#include<sys/wait.h>

using namespace LogModule;

using func_t = std::function<std::string(std::string &)>;

// 默认等待队列最大长度
const int default_ln = 5;

class Server
{

public:
    Server(int port, func_t func)
        : _port(port),
          _isrunning(false),
          _func(func)

    {
    }

    // 初始化
    void Init()
    {
        // 创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::ERROR) << "socket error";
            exit(ExitCode::SOCkET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success!";

        InetAddr addr(_port);
        // 进行bind绑定
        int n = bind(_listensockfd, addr.GetAddr(), addr.SockLen());
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "bind error";
            exit(ExitCode::BIND_ERR);
        }

        LOG(LogLevel::INFO) << "bind success!";

        // 进行listen监听
        n = listen(_listensockfd, default_ln);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "listen error";
            exit(ExitCode::LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success!";
    }

    void Service(int sockfd, InetAddr &peer)
    {
        char buffer[4096];
        while (1)
        {
            // 从sockfd当中获取对应的数据
            ssize_t n = read(sockfd, buffer, sizeof(buffer));
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "read error";
                close(sockfd);
                break;
            }
            else if (n == 0)
            {

                LOG(LogLevel::INFO) << "clients quit";
                close(sockfd);
                break;
            }
            else
            {
                buffer[n] = 0;
                std::string ret = "client say:";
                ret += buffer;
                LOG(LogLevel::INFO) << peer.StringAddr() << ",Client say:" << buffer;
                // 将数据写入到sockfd对应的文件
                ssize_t n = write(sockfd, ret.c_str(), ret.size());
            }
        }
    }

    // 启动服务器
    void Start()
    {
        _isrunning = true;
        char buffer[1024];
        while (_isrunning)
        {
            sockaddr_in addr;
            unsigned int len = sizeof(addr);
            // 使用accept发消息
            int sockfd = accept(_listensockfd, COW(addr), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }
            LOG(LogLevel::INFO) << "accept success";
            InetAddr peer(addr);

            pid_t fd = fork();
            if (fd < 0)
            {
                LOG(LogLevel::ERROR) << "fork error";
                exit(ExitCode::FORK_ERR);
            }
            else if (fd == 0)
            {
                close(_listensockfd);
                if (fork() > 0)
                {
                    exit(ExitCode::OK);
                }
                Service(sockfd, peer);
                exit(ExitCode::OK);
            }
            else
            {
                close(sockfd);
                int ret=waitpid(fd,nullptr,0);
                (void)ret;


            }

            //Service(sockfd, peer);
        }

        // close(_listensockfd);
    }

private:
    // 套接字
    int _listensockfd;
    // 端口号
    uint16_t _port;
    // 是否运行标志位
    bool _isrunning;
    // 回调函数
    func_t _func;
};
